package com.zenithmind.document.pojo.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Min;
import java.time.LocalDateTime;

/**
 * 文档统计创建DTO
 * 遵循单一职责原则：专注于统计创建数据传输
 * 遵循开闭原则：通过验证注解支持扩展
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Data
@Schema(description = "文档统计创建DTO")
public class DocumentStatisticsCreateDTO {

    @Schema(description = "文档ID", required = true, example = "doc123456")
    @NotBlank(message = "文档ID不能为空")
    private String documentId;

    @Schema(description = "查看次数", example = "100")
    @Min(value = 0, message = "查看次数不能为负数")
    private Long viewCount;

    @Schema(description = "下载次数", example = "25")
    @Min(value = 0, message = "下载次数不能为负数")
    private Long downloadCount;

    @Schema(description = "分享次数", example = "10")
    @Min(value = 0, message = "分享次数不能为负数")
    private Long shareCount;

    @Schema(description = "收藏次数", example = "15")
    @Min(value = 0, message = "收藏次数不能为负数")
    private Long favoriteCount;

    @Schema(description = "评论次数", example = "8")
    @Min(value = 0, message = "评论次数不能为负数")
    private Long commentCount;

    @Schema(description = "点赞次数", example = "20")
    @Min(value = 0, message = "点赞次数不能为负数")
    private Long likeCount;

    @Schema(description = "评分次数", example = "12")
    @Min(value = 0, message = "评分次数不能为负数")
    private Long ratingCount;

    @Schema(description = "平均评分", example = "4.5")
    private Double averageRating;

    @Schema(description = "总评分", example = "54.0")
    private Double totalRating;

    @Schema(description = "独立访客数", example = "80")
    @Min(value = 0, message = "独立访客数不能为负数")
    private Long uniqueVisitors;

    @Schema(description = "总访问时长（秒）", example = "3600")
    @Min(value = 0, message = "总访问时长不能为负数")
    private Long totalViewDuration;

    @Schema(description = "平均访问时长（秒）", example = "120")
    private Double averageViewDuration;

    @Schema(description = "跳出率", example = "0.25")
    private Double bounceRate;

    @Schema(description = "转化率", example = "0.15")
    private Double conversionRate;

    @Schema(description = "最后查看时间", example = "2025-01-09T15:30:00")
    private LocalDateTime lastViewTime;

    @Schema(description = "最后下载时间", example = "2025-01-09T14:20:00")
    private LocalDateTime lastDownloadTime;

    @Schema(description = "最后分享时间", example = "2025-01-09T13:10:00")
    private LocalDateTime lastShareTime;

    @Schema(description = "统计日期", example = "2025-01-09T00:00:00")
    private LocalDateTime statisticsDate;

    @Schema(description = "统计类型", example = "DAILY", allowableValues = {"DAILY", "WEEKLY", "MONTHLY", "YEARLY", "TOTAL"})
    private String statisticsType;

    @Schema(description = "数据来源", example = "SYSTEM", allowableValues = {"SYSTEM", "MANUAL", "IMPORT", "SYNC"})
    private String dataSource;

    @Schema(description = "扩展统计数据", example = "{\"mobileViews\": 30, \"desktopViews\": 70}")
    private String extendedData;

    @Schema(description = "备注", example = "系统自动统计")
    private String remarks;

    /**
     * 创建基础统计
     */
    public static DocumentStatisticsCreateDTO createBasicStatistics(String documentId) {
        DocumentStatisticsCreateDTO dto = new DocumentStatisticsCreateDTO();
        dto.setDocumentId(documentId);
        dto.setViewCount(0L);
        dto.setDownloadCount(0L);
        dto.setShareCount(0L);
        dto.setFavoriteCount(0L);
        dto.setCommentCount(0L);
        dto.setLikeCount(0L);
        dto.setRatingCount(0L);
        dto.setAverageRating(0.0);
        dto.setTotalRating(0.0);
        dto.setUniqueVisitors(0L);
        dto.setTotalViewDuration(0L);
        dto.setAverageViewDuration(0.0);
        dto.setBounceRate(0.0);
        dto.setConversionRate(0.0);
        dto.setStatisticsDate(LocalDateTime.now());
        dto.setStatisticsType("DAILY");
        dto.setDataSource("SYSTEM");
        return dto;
    }

    /**
     * 创建查看统计
     */
    public static DocumentStatisticsCreateDTO createViewStatistics(String documentId, Long viewCount, Long uniqueVisitors) {
        DocumentStatisticsCreateDTO dto = createBasicStatistics(documentId);
        dto.setViewCount(viewCount);
        dto.setUniqueVisitors(uniqueVisitors);
        dto.setLastViewTime(LocalDateTime.now());
        return dto;
    }

    /**
     * 创建下载统计
     */
    public static DocumentStatisticsCreateDTO createDownloadStatistics(String documentId, Long downloadCount) {
        DocumentStatisticsCreateDTO dto = createBasicStatistics(documentId);
        dto.setDownloadCount(downloadCount);
        dto.setLastDownloadTime(LocalDateTime.now());
        return dto;
    }

    /**
     * 创建评分统计
     */
    public static DocumentStatisticsCreateDTO createRatingStatistics(String documentId, Long ratingCount, 
                                                                   Double totalRating, Double averageRating) {
        DocumentStatisticsCreateDTO dto = createBasicStatistics(documentId);
        dto.setRatingCount(ratingCount);
        dto.setTotalRating(totalRating);
        dto.setAverageRating(averageRating);
        return dto;
    }

    /**
     * 验证DTO数据
     */
    public boolean isValid() {
        if (documentId == null || documentId.trim().isEmpty()) return false;
        
        // 验证计数字段不为负数
        if (viewCount != null && viewCount < 0) return false;
        if (downloadCount != null && downloadCount < 0) return false;
        if (shareCount != null && shareCount < 0) return false;
        if (favoriteCount != null && favoriteCount < 0) return false;
        if (commentCount != null && commentCount < 0) return false;
        if (likeCount != null && likeCount < 0) return false;
        if (ratingCount != null && ratingCount < 0) return false;
        if (uniqueVisitors != null && uniqueVisitors < 0) return false;
        if (totalViewDuration != null && totalViewDuration < 0) return false;
        
        // 验证评分范围
        if (averageRating != null && (averageRating < 0 || averageRating > 5)) return false;
        
        // 验证比率范围
        if (bounceRate != null && (bounceRate < 0 || bounceRate > 1)) return false;
        if (conversionRate != null && (conversionRate < 0 || conversionRate > 1)) return false;
        
        return true;
    }

    /**
     * 计算平均评分
     */
    public void calculateAverageRating() {
        if (ratingCount != null && ratingCount > 0 && totalRating != null) {
            averageRating = totalRating / ratingCount;
        } else {
            averageRating = 0.0;
        }
    }

    /**
     * 计算平均访问时长
     */
    public void calculateAverageViewDuration() {
        if (viewCount != null && viewCount > 0 && totalViewDuration != null) {
            averageViewDuration = totalViewDuration.doubleValue() / viewCount;
        } else {
            averageViewDuration = 0.0;
        }
    }

    /**
     * 计算跳出率
     */
    public void calculateBounceRate() {
        if (viewCount != null && viewCount > 0 && uniqueVisitors != null) {
            // 简化计算：假设单次访问的用户为跳出用户
            long singleViewUsers = Math.max(0, uniqueVisitors - (viewCount - uniqueVisitors));
            bounceRate = ((double) singleViewUsers) / uniqueVisitors;
        } else {
            bounceRate = 0.0;
        }
    }

    /**
     * 计算转化率
     */
    public void calculateConversionRate() {
        if (viewCount != null && viewCount > 0) {
            long conversions = 0;
            if (downloadCount != null) conversions += downloadCount;
            if (shareCount != null) conversions += shareCount;
            if (favoriteCount != null) conversions += favoriteCount;

            conversionRate = ((double) conversions) / viewCount;
        } else {
            conversionRate = 0.0;
        }
    }

    /**
     * 获取总互动次数
     */
    public Long getTotalInteractions() {
        long total = 0;
        if (viewCount != null) total += viewCount;
        if (downloadCount != null) total += downloadCount;
        if (shareCount != null) total += shareCount;
        if (favoriteCount != null) total += favoriteCount;
        if (commentCount != null) total += commentCount;
        if (likeCount != null) total += likeCount;
        return total;
    }

    /**
     * 是否有评分数据
     */
    public boolean hasRatingData() {
        return ratingCount != null && ratingCount > 0;
    }

    /**
     * 是否有访问数据
     */
    public boolean hasViewData() {
        return viewCount != null && viewCount > 0;
    }

    /**
     * 是否有下载数据
     */
    public boolean hasDownloadData() {
        return downloadCount != null && downloadCount > 0;
    }

    /**
     * 统计类型枚举
     */
    public enum StatisticsType {
        DAILY("日统计"),
        WEEKLY("周统计"),
        MONTHLY("月统计"),
        YEARLY("年统计"),
        TOTAL("总统计");

        private final String description;

        StatisticsType(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }
    }

    /**
     * 数据来源枚举
     */
    public enum DataSource {
        SYSTEM("系统自动"),
        MANUAL("手动录入"),
        IMPORT("数据导入"),
        SYNC("同步数据");

        private final String description;

        DataSource(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }
    }
}
